import json
import subprocess
from threading import Thread

import psutil
from channels.generic.websocket import JsonWebsocketConsumer

from oplatform.models import ChannelData
from utils.rest.decorator import action_name

current_process = None


path = '/var/www/channels.txt'
all_channels = []


def clean_channel():
    ChannelData.objects.all().delete()


def create_channel(path):
    id = 1
    with open(path, 'r', encoding='utf-8', errors='ignore') as file:
        lines = file.readlines()
        for line in lines:
            if ':' in line:
                channel_split = line.split(':')
                name = channel_split[0]
                provider_name = channel_split[1]
                coderate = channel_split[2]
                freq = channel_split[3]
                modulation = channel_split[4]
                delivery_system = channel_split[5]
                srate = channel_split[6]
                sid = channel_split[7]
                pmt = channel_split[8]
                pcr = channel_split[9]
                video_id = channel_split[10]
                audio_id = channel_split[11]
                subtitle = channel_split[12]
                caid = channel_split[13]
                channel_item = {
                    'id': id,
                    'name': name,
                    'provider_name': provider_name,
                    'coderate': coderate,
                    'freq': freq,
                    'modulation': modulation,
                    'delivery_system': delivery_system,
                    'srate': srate,
                    'sid': sid,
                    'pmt': pmt,
                    'pcr': pcr,
                    'video_id': video_id,
                    'audio_id': audio_id,
                    'subtitle': subtitle,
                    'caid': caid,
                }
                all_channels.append(channel_item)
                id += 1
                print(id)
        for channel in all_channels:
            ChannelData.objects.get_or_create(
                id=channel.get('id'),
                name=channel.get('name'),
                provider_name=channel.get('provider_name'),
                coderate=channel.get('coderate'),
                freq=channel.get('freq'),
                modulation=channel.get('modulation'),
                delivery_system=channel.get('delivery_system'),
                srate=channel.get('srate'),
                sid=channel.get('sid'),
                pmt=channel.get('pmt'),
                pcr=channel.get('pcr'),
                video_id=channel.get('video_id'),
                audio_id=channel.get('audio_id'),
                subtitle=channel.get('subtitle'),
                caid=channel.get('caid'),
            )


def run(p):
    flag = True
    while flag:
        with open('/var/www/channels.txt', 'r') as f:
            if not psutil.pid_exists(p) and f.readline() != '':
                flag = False
                clean_channel()
                create_channel(path)


@action_name('ping命令')
class ScanChannelTimeInfoConsumer(JsonWebsocketConsumer):

    def websocket_connect(self, event):
        self.accept()

    def websocket_disconnect(self, message):
        cmd = 'kill -9 ' + str(self.pid)
        subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
        super(ScanChannelTimeInfoConsumer, self).websocket_disconnect(message)

    def websocket_receive(self, event):
        global current_process
        is_start = json.loads(event.get('text')).get('data')
        if is_start != '':
            cmd = '/opt/w_scan -fc > /var/www/channels.txt'
            p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            self.p = p
            self.pid = p.pid
            current_process = p
            thread = Thread(target=run, args=(p.pid, ))
            thread.start()
            if p.poll() is None:
                line = p.stdout.readline()
                line = line.strip()
                if '/opt/w_scan' not in str(line, encoding="utf-8"):
                    self.send_json({
                        'info': str(line, 'utf-8')
                    })
        else:
            if current_process.poll() is None:
                line = current_process.stdout.readline()
                line = line.strip()
                self.send_json({
                    'info': str(line, 'utf-8')
                })



